package com.pixiv.controller;


import cn.hutool.json.JSONObject;
import com.pixiv.Entity.TitlePicture;
import com.pixiv.Entity.User;
import com.pixiv.service.TitleService;
import com.pixiv.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;


@Controller
@RequestMapping("search")
public class SearchController {

    @Autowired
    private TitleService titleService;
    @Autowired
    private UserService userService;

    @RequestMapping("find")
    public ModelAndView find(HttpServletRequest req){

        String context = req.getParameter("context");

        HttpSession hs = req.getSession();
        User u = (User) hs.getAttribute("GLOBAL_USER_OBJECT");
        u.getVar().push_vector("searchTitleInformation",context);

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("pixiv/search/search");
        return modelAndView;
    }

    @RequestMapping("gotoUser")
    public ModelAndView findUser(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("pixiv/search/search_user");
        return modelAndView;
    }

    @RequestMapping("gotoTitle")
    public ModelAndView findTitle(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("pixiv/search/search");
        return modelAndView;
    }

    @ResponseBody
    @RequestMapping("searchTitle")
    public String searchTitle(HttpServletRequest req){
        HttpSession hs = req.getSession();
        User u = (User) hs.getAttribute("GLOBAL_USER_OBJECT");
        String context = (String) u.getVar().get_vector("searchTitleInformation");
        List<TitlePicture> al = titleService.SearchTitle(context);
        JSONObject json=new JSONObject();
        json.accumulate("titles",al);

        if (al.size() > 0)
            json.accumulate("flag",1);
        else
            json.accumulate("flag",0);
        return json.toString();

    }


}
